package com.lx.chong.controller;


import com.lx.chong.common.Result;
import com.lx.chong.model.ProConfig;
import com.lx.chong.service.impl.ProConfigServiceImpl;
import com.lx.chong.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 通用上传类
 *
 * @author: whh
 * @date: 2018/2/1
 */
@RestController
@Slf4j
@CrossOrigin
public class UploadController {

    @Autowired
    private ProConfigServiceImpl proConfigService;

    /**
     * 主上传方法
     *
     * @param request     request
     * @param concreteUrl upload文件下具体路径
     * @return
     */
    public synchronized Result upload(HttpServletRequest request, String concreteUrl, Long id) {
        ProConfig proConfig = proConfigService.findOne(id);
        String webServerUploadInforUrl = proConfig.getUploadInfoUrl() + "/" + PropertiesUtil.get("projectName") + "/";
        //是否是linux
        String concreteLocation = "";
        if (proConfig.getIsLinux() == 1) {
            concreteLocation = "/";
        } else {
            concreteLocation = "\\\\";
        }
        String webServerUploadInfoLocation = proConfig.getUploadInfoLocation() + concreteLocation + PropertiesUtil.get("projectName") + concreteLocation;
        log.info("[start] upload");
        // 网站地址
        log.info("[webServerUploadInforUrl]:" + webServerUploadInforUrl);
        // 网站部署物理绝对路径地址
        log.info("[webServerUploadInforLocation]:" + webServerUploadInfoLocation);
        // 转换为文件类型的request
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获取对应file对象
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Iterator<String> fileIterator = multipartRequest.getFileNames();
        // 文件存放绝对路径
        String path = webServerUploadInfoLocation + id + concreteLocation + concreteUrl;
        Map resultMap = new ConcurrentHashMap<String, String>(Collections.EMPTY_MAP);
        while (fileIterator.hasNext()) {
            String fileKey = fileIterator.next();
            // 获取对应文件
            MultipartFile multipartFile = fileMap.get(fileKey);
            if (multipartFile.getSize() != 0L) {
                String fileName = "";
                try {
                    String[] split = multipartFile.getOriginalFilename().split("\\.", -1);
                    fileName = System.currentTimeMillis() + "." + split[split.length == 0 ? 0 : split.length - 1];
                    String strPath = path;
                    File filePath = new File(strPath);
                    if (!filePath.exists()) {
                        filePath.mkdirs();
                    }
                    multipartFile.transferTo(new File(path, fileName));
                } catch (Exception e) {
                    log.error(e.toString());
                }
                // 暂时配置到本地的nginx文件服务器
                resultMap.put("url", webServerUploadInforUrl + id + "/" + concreteUrl + "/" + fileName);
                resultMap.put("link", webServerUploadInforUrl + id + "/" + concreteUrl + "/" + fileName);
                resultMap.put("title", fileName);
                resultMap.put("originalName", multipartFile.getOriginalFilename());
                resultMap.put("state", "SUCCESS");
                log.info("[end] /summernote/fileupload");
            } else {
                log.info("[error] /summernote/fileupload");
                resultMap.put("message", "ERROR");
                resultMap.put("info", "fileIsNull");
            }
        }
        // 针对ueditor返回值固定配置 ,需要一个 'state, url, title 为最外层属性'
        Result result = new Result();
        result.setData(resultMap);
        return result;
    }

    /**
     * 人员信息资料上传
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/uploadPerson")
    public Result uploadPersonInfo(HttpServletRequest request, Long id) {
        return upload(request, "person", id);
    }

    /**
     * 图片信息资料上传
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/uploadImage")
    public Result uploadImage(HttpServletRequest request, Long organizationId, String concreteUrl) {
        return upload(request, concreteUrl, organizationId);
    }

    /**
     * 单位资料上传
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/uploadOrganization")
    public Result uploadOrganizationInfo(HttpServletRequest request, Long organizationId) {
        return upload(request, "organization", organizationId);
    }

    /**
     * 可下载文件上传
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/uploadDownload")
    public Result uploadDownloadInfo(HttpServletRequest request, Long organizationId) {
        return upload(request, "download", organizationId);
    }

    /**
     * 项目信息上传
     *
     * @param request
     * @return
     */
    @PostMapping(value = "/uploadProject")
    public Result uploadProjectInfo(HttpServletRequest request, Long organizationId) {
        return upload(request, "project", organizationId);
    }

    /**
     * 删除文件，可以是文件或文件夹
     *
     * @param fileName 要删除的文件名
     * @return 删除成功返回true，否则返回false
     */
    public boolean delete(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            System.out.println("删除文件失败:" + fileName + "不存在！");
            return false;
        } else {
            if (file.isFile()) {
                return deleteFile(fileName);
            } else {
                return true;
            }
        }
    }

    /**
     * 删除单个文件
     *
     * @param fileName 要删除的文件的文件名
     * @return 单个文件删除成功返回true，否则返回false
     */
    public static boolean deleteFile(String fileName) {
        File file = new File(fileName);
        // 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
        if (file.exists() && file.isFile()) {
            if (file.delete()) {
                System.out.println("删除单个文件" + fileName + "成功！");
                return true;
            } else {
                System.out.println("删除单个文件" + fileName + "失败！");
                return false;
            }
        } else {
            System.out.println("删除单个文件失败：" + fileName + "不存在！");
            return false;
        }
    }

}
